#URL = "http://www.libsdl.org/tmp/SDL-%(VERSION)s.zip"
URL = "file://../prescan/additions/sdl/SDL-%(VERSION)s.zip"
VERSIONS = ["1.3"] # Is unstable
DEFAULT_VERSION = "1.3"
DEPENDS = ["dx7_min"]

from source.builders import VisualStudioBuilder
import os, sys
import shutil
import ext.patch

class SDLBuilder( VisualStudioBuilder ):

  def patch(self):
    os.chdir( self.extractedpath )
    patchstr = ""
    with open(sys.path[0]+"/library/additions/sdl/SDL_No_audio.patch", 'r') as patchfile:
      patchstr = patchfile.read()
    p = ext.patch.fromstring(patchstr)
    print "Patch applied: ", p.apply()

  def configure(self):
    os.chdir( os.path.join( self.extractedpath, "VisualC" ) )

    self.solution =  "SDL_VS2008.sln"
    self.vcprojs = ["SDLmain", "SDL"]
    
    input  = r'.*AdditionalIncludeDirectories="..\\..\\include"'
    output = r'AdditionalIncludeDirectories="..\..\include;%s"' % self.dependencies["dx7_min"].getincludedir()
    self.replaceLinesInFile(r"SDL\SDL_VS2008.vcproj", [(input, output)] )

  def make(self):
    os.chdir( os.path.join( self.extractedpath, "VisualC" ) )
    config = "Debug|" if self.debug else "Release|"
    config += "x64" if self.machine.bits == 64 else "win32"
    
    for project in self.vcprojs:
        self.execute(["devenv.com", self.solution, "/Rebuild", config, "/project", project] )
        
  def install(self):
    os.chdir( self.extractedpath )

    # Copy include
    if os.path.exists( os.path.join(self.targetpath(), "include") ):
      shutil.rmtree( os.path.join(self.targetpath(), "include") )
    self.copydir( "include", os.path.join(self.targetpath(), "include") )

    # Copy SDL dll/slibs
    dir = "x64" if self.machine.bits == 64 else ""
    dir = os.path.join("VisualC", "SDL", dir, "Debug" if self.debug else "Release")
    self.copyfile( os.path.join(dir, "SDL.dll"), os.path.join(self.targetpath(), "bin") )
    self.copyfile( os.path.join(dir, "SDL.lib"), os.path.join(self.targetpath(), "lib") )

    # Copy SDLmain lib
    dir = "x64" if self.machine.bits == 64 else ""
    dir = os.path.join("VisualC", "SDLmain", dir, "Debug" if self.debug else "Release")
    self.copyfile( os.path.join(dir, "SDLmain.lib"), os.path.join(self.targetpath(), "lib") )

    if self.debug:
      for files in ((("bin", "SDL.dll"),("bin", "SDLd.dll")),
                   (("lib", "SDL.lib"),("lib", "SDLd.lib")),
                   (("lib", "SDLmain.lib"),("lib", "SDLmaind.lib"))):
        sourcefile = os.path.join(self.targetpath(), *files[0])
        targetfile = os.path.join(self.targetpath(), *files[1])
        if os.path.exists(targetfile):
            os.remove( targetfile )
        os.rename( sourcefile, targetfile )


BUILDER = SDLBuilder
